class Game{
    constructor(){
        this.sky = new Sky();
        this.bird = new Bird();
        //柱子对生成
        this.pipeProducer = new PipePareProducer();
        this.timer = null;
        this.tick = 20;
        this.gameOver = false;
    }

    start(){
        if(this.timer){
            return;
        }
        
        this.pipeProducer.startProduce();
        this.timer = setInterval(() =>{
            const duration = this.tick / 1000;
            this.bird.startFly();
            this.sky.move(duration);
            this.bird.move(duration);
            this.pipeProducer.pairs.forEach(pair =>{
                pair.move(duration);
            })
            
            if(this.isGameOver()){
                this.stop();
                this.gameOver = true;
                alert("游戏结束");
                window.location.reload();
            }

        },this.tick)
        
    }





    /**
     * 判断两个矩形是否碰撞
     * @param {*} rec1 
     * @param {*} rec2 
     * @returns 
     */
    isHit(rec1,rec2){
        let centerX1 = rec1.left + rec1.width / 2;
        let centerY1 = rec1.top + rec1.height / 2;
        let centerX2 = rec2.left + rec2.width / 2;
        let centerY2 = rec2.top + rec2.height / 2;
        let disX = Math.abs(centerX1 - centerX2);
        let disY = Math.abs(centerY1 - centerY2);
        if(disX < (rec1.width + rec2.width) / 2 && 
           disY < (rec1.height + rec2.height) / 2
        ){
            return true;
        }else{
            return false;
        }

    }

    isGameOver(){
        if(this.bird.top === this.bird.maxY){
            return  true;
        }
        for (let i = 0; i < this.pipeProducer.pairs.length; i++) {
            const pair = this.pipeProducer.pairs[i];
            if (this.isHit(this.bird, pair.upPipe) || this.isHit(this.bird, pair.downPipe)) {
                return true;
            }
            return false;
            
        }
        
    }

    stop(){
        clearInterval(this.timer);
        this.timer = null;
        this.bird.stopFly();
        this.pipeProducer.stopProduce();
    }

    regEvent(){
        window.onkeydown = (e) =>{
            if(e.key === "Enter"){
                if(this.timer){
                    this.stop();
                }else{
                    this.start();
                }
            }
            else if(e.key === " "){
                this.bird.jump();
            }

        }
    }
}

var ga = new Game();
ga.regEvent();